'''
Created on 19/03/2010

@author: eh01
'''
from runtime.task import Task
from datastore.resource import Resource
import httplib
import logging

class LoginTask(Task):
    """This class is a daemon task. It processes requests from httpserver::RequestHandler
    and return Spaces resources.

    *Usage examples*::

        example code

    *Common Arguments for Class methods*:
        <arguments>
    
    *Audience*:
        <audience>
    
    *Constants*:
        .. data:: constant_1
        
            constant_1 is used for ......
        
        .. data:: constant_2
        
            constant_2 is used for ......
    """

    def cb_start(self, method, uri, new_uri, result, context, **kwargs):
        """This function is called when the task starts. 
        
        :param method: <class> or <type>
        :param uri: The task Uri.
        :param new_uri: <class> or <type>
        :param result: <class> or <type>
        :param context: <class> or <type>
        :param kwargs: <class> or <type>
        """
        
        self.logger.log(logging.DEBUG, "***************** uri (%s), new_uri (%s)" % (uri, new_uri))
        
        # Make sure we look for ALL Uris that are children of our task Uri.
        # (i.e. make a collection of our Uri. 
        #
        # All 'put' messages to this task are interpreted as requests for Spaces Resources.
        #
        self.spaces_context.process(uri.login.submit, put='cb_login_submit')
    
    def cb_login_submit(self, method, uri, return_value, result, context, **kwargs):
        """This method handles the login submit.
        
        :param method: <class> or <type>
        :param uri: The task Uri.
        :param return_value: Resource
        :param result: <class> or <type>
        :param context: <class> or <type>
        :param kwargs: <class> or <type>
        """
        
        rs = Resource()
        post_data = return_value.get_var(Resource.KEY_URI_SERVICES_TYPE_HTTP_REQUEST_DATA)
        username = post_data['username']
        password = post_data['password']
        # hardcoded username and password. We aren't trying to demonstrate how to do 
        # authentication in this reference implementation.
        if username and username == 'HAF' and password and password == 'eDA':
            rs.http_response_code = httplib.FOUND
            rs.http_headers = {'Location': '/menu'}
        else:
            rs.set_var(Resource.KEY_URI_SERVICES_TYPE_HTTP_SITE_ACTION_RESULT, 'login')
            rs.error_message = 'Incorrect username and password.'
        
        id = context.uuid()
        request_uri = uri.requests.add(str(id))
        context.put(request_uri.response, rs)
        # return a copy of the uri as we dont want changes to the return uri by the caller to affect 
        # how we use the uri
        return (True, request_uri.uri_copy())        